class FollowupRecordService

  def self.add(json)
    !FollowupRecord.create!(
      companies_id: json[:companies_id],
      contacts_id: json[:contacts_id],
      followup_time: json[:followup_time],
      followup_employee_code: json[:followup_employee_code],
      contact_channel: json[:contact_channel],
      followup_phase: json[:followup_phase],
      followup_status: json[:followup_status],
      note: json[:note],
      creator_id: json[:creator_id]      
    ).new_record?
  end

  def self.batch_update_followup_status_by_ids(ids)
    FollowupRecord.where('id': ids).update_all('followup_status': 1)
  end

  def self.query_follow_record_by_id(id)
    FollowupRecord.find_by('id': id)
  end
  
  def self.update(json)
    record = FollowupRecord.find_by('id': json[:id])
    return false if record.blank?

    record.followup_time = json[:followup_time]
    record.followup_employee_code = json[:followup_employee_code]
    record.contacts_id = json[:contacts_id]
    record.contact_channel = json[:contact_channel]
    record.followup_phase = json[:followup_phase]
    record.followup_status = json[:followup_status]
    record.note = json[:note]

    record.save
  end

  def self.delete_by_id(id)
    FollowupRecord.where('id': id).delete_all
  end
  
  def self.query_by_companies_id(companies_id)
    followup_records =  FollowupRecord.includes(:contact, :followup_employee, :create_employee).where('companies_id': companies_id).to_a
    return { data: nil } if followup_records.size == 0

    followup_status_done_arr = followup_records.select{ |item| item.followup_status == 1 }
    followup_status_todo_arr = followup_records.select{ |item| item.followup_status == 0 }

    { 
      data: {      
        followup_records_done: followup_status_done_arr.map{ |item| format_followup_record(item) },
        followup_records_todo: followup_status_todo_arr.map{ |item| format_followup_record(item) },
        done_count: followup_status_done_arr.size,
        todo_count: followup_status_todo_arr.size
     }
   }
  end

  # 格式化输出跟进记录
  def self.format_followup_record(record)
    return {} if record.blank?
    
    {
      id: record.id,
      followup_time: record.followup_time,
      followup_employee_name: (record.followup_employee.emp_name_cn if record.followup_employee.present?),
      created_at: record.created_at,
      creator_employee_name: (record.create_employee.emp_name_cn if record.create_employee.present?),
      contact_name: (record.contact.name if record.contact.present?),
      contact_channel: record.contact_channel,
      followup_phase: record.followup_phase,
      note: record.note
    }
  end
  
end